<template>
	<Page>
		<Topbar hideMenu />
		<Content>
			<Panel>
				<view class="left">
					<MyInfo :data="workInfo" backUrl="/pages/workbench/rework/index" />
				</view>
				<view class="right" v-if="workInfo.reworkStatus === '未开始'">
					<Empty text="当前工单未开始返工..." />
					<div class="btn-group">
						<Button large type="success" @click="open2">
							开始
						</Button>
					</div>
				</view>
				<FormWrap header title="返工执行" height="67vh" v-if="workInfo.reworkStatus === '处理中'">
					<u--form :labelPosition="labelPosition" labelAlign="left" :model="model" :rules="rules" ref="uForm"
						labelWidth="14rem" :labelStyle="{'margin-bottom' : labelPosition === 'top' ? '2rem' : '0'}"
						style="padding: 0 5rem;">
						<u-form-item label="处理结果" prop="processingType">
							<u-radio-group v-model="model.processingType" placement="row">
								<u-radio v-for="(item, index) in ['合格', '报废']" :key="index" :label="item" :name="item"
									@change="changeprocessingType">
								</u-radio>
							</u-radio-group>
						</u-form-item>
						<view class="sub-title">
							处理结果
						</view>
						<u-row justify="space-between">
							<u-col span="5">
								<u-form-item label="班次" prop="shift" required class="label-fwn">
									<uni-data-select v-model="model.shift" :modelValue="model.shift" :localdata="shifts"
										format="{label}" placeholder="请选择" :clear="false" @change='shiftChange'>
									</uni-data-select>
								</u-form-item>
							</u-col>
							<u-col span="5">
								<u-form-item label="班次时间" prop="shiftTime" required class="label-fwn">
									<DatePicker v-model="model.shiftTime" @change="shiftTimeChange" />
								</u-form-item>
							</u-col>
						</u-row>
						<!-- <u-row justify="space-between" v-if="model.processingType === '报废'">
                            <u-col span="5">
                                <u-form-item label="返工开始时间" prop="startTime" required class="label-fwn">
                                    <DatePicker v-model="model.startTime" mode="datetime" />
                                </u-form-item>
                            </u-col>
                            <u-col span="5">
                                <u-form-item label="返工结束时间" prop="endTime" required class="label-fwn">
                                    <DatePicker v-model="model.endTime" mode="datetime" />
                                </u-form-item>
                            </u-col>
                        </u-row> -->
						<u-row justify="space-between">
							<u-col span="5">
								<u-form-item label="提报方式" prop="reportingMethod" required class="label-fwn">
									<uni-data-select v-model="model.reportingMethod" :modelValue="model.reportingMethod"
										:localdata="reportingMethods" format="{label}" :clear="false"
										placeholder="请选择"></uni-data-select>
								</u-form-item>
							</u-col>
							<u-col span="5">
								<u-form-item :label="fmtlabel()" prop="reportedQuantity" required class="label-fwn">
									<InputNumberField v-model.number="model.reportedQuantity" :min="0" :max="999999"
										:placeholder="model.processingType === '报废'? '自动计算' : '请输入'"
										:disabled="model.processingType === '报废'">
										<template slot="suffix" v-if="model.reportingMethod==='按重量'">
											{{ workInfo.unit }}
										</template>
									</InputNumberField>
								</u-form-item>
							</u-col>
						</u-row>
						<u-row justify="space-between">
							<u-col span="5" v-if="model.processingType === '合格'">
								<u-form-item label="入库仓库" prop="inboundWarehouse" required class="label-fwn">
									<uni-data-select v-model="model.inboundWarehouse"
										:modelValue="model.inboundWarehouse" :localdata="wareHouses" format="{label}"
										:clear="false" placeholder="请选择" @change="wareHouseChange"></uni-data-select>
								</u-form-item>
							</u-col>
							<u-col span="5">
								<u-form-item label="备注" prop="remarks" class="label-fwn">
									<InputField v-model="model.remarks" :maxlength="100" />
								</u-form-item>
							</u-col>
						</u-row>
						<u-form-item label="报废原因" prop="outReason" class="label-top"
							v-if="model.processingType === '报废'">
							<u-radio-group v-model="model.outReason" placement="row">
								<u-radio v-for="(item, index) in reasons" :key="index" :label="item.label"
									:name="item.value">
								</u-radio>
							</u-radio-group>
						</u-form-item>
						<view class="sub-title" v-if="model.processingType === '报废'">
							不良项
						</view>
						<view class="ng-list" v-if="model.processingType === '报废'">
							<u-form-item v-for="(item, index) in model.ngList" :key="index" :label="item.ngCode"
								class="label-fwn">
								<InputNumberField v-model.number="item.ngNumber" placeholder="请输入数量" :min="0"
									:max="9999" @blur="autoTotal" />
							</u-form-item>
						</view>
					</u--form>
					<template slot="footer">
						<Button large type="primary" @click="open1" style="margin-left: 3rem;">
							提交
						</Button>
					</template>
				</FormWrap>
			</Panel>
		</Content>
		<Modal title="确认提交吗？" ref="popup1" @confirm="confirm1" />
		<Modal title="确认开始吗？" ref="popup2" @confirm="confirm2" />
	</Page>
</template>

<script>
	import Page from "@/components/page/index.vue";
	import Topbar from "@/components/topbar/index.vue";
	import Content from "@/components/content/index.vue";
	import Panel from "@/components/panel/index.vue";
	import Empty from "@/components/empty/index.vue";
	import Button from "@/components/button/index.vue";
	import FormWrap from '@/components/formWrap/index.vue';
	import InputField from '@/components/formField/inputField/index.vue';
	import InputCaptcheField from '@/components/formField/inputCaptcheField/index.vue';
	import InputNumberField from '@/components/formField/inputNumberField/index.vue';
	import NumberBoxField from '@/components/formField/numberBoxField/index.vue';
	import DatePicker from '@/components/formField/datePicker/index.vue';
	import Modal from '@/components/modal/index.vue';
	import fetch from "@/utils/fetch";
	import MyInfo from "./info/index.vue";
	import {
		getDevice
	} from "@/store/user.js";
	import filter from "@/utils/filter";
	import {
		timeIsBetweenTimeRange
	} from "@/utils/date";

	export default {
		components: {
			Page,
			Topbar,
			Content,
			Panel,
			Empty,
			Button,
			FormWrap,
			InputField,
			InputCaptcheField,
			InputNumberField,
			NumberBoxField,
			DatePicker,
			Modal,
			MyInfo
		},
		data() {
			return {
				tableData: [],
				pageSize: 10,
				pageCurrent: 1,
				total: 0,
				loading: false,
				workInfo: {},
				labelPosition: 'left',
				shifts: [],
				reportingMethods: [{
						label: '按数量',
						value: '按数量',
					},
					{
						label: '按重量',
						value: '按重量',
					}
				],
				wareHouses: [],
				reasons: [],
				model: {
					processingType: '合格',
					shift: '',
					shiftTime: Number(new Date()),
					reportingMethod: '按数量',
					reportedQuantity: '',
					inboundWarehouse: '仓库1',
					outReason: '',
					ngList: [],
				},
				rules: {
					'shift': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'reportingMethod': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'inboundWarehouse': {
						type: 'string',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
					'reportedQuantity': {
						type: 'number',
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					},
				},
			}
		},
		methods: {
			getWorkOrderInfo(applicationNumber) {
				fetch('get', '/dms/mobileEnd/getReworkByWorkOrder', {
					applicationNumber
				}).then((res) => {
					this.workInfo = res;
				});
			},
			shiftChange(val) {
				const arg = this.shifts.find(item => item.label == val)
				if (arg) {
					this.model.shiftId = arg.id;
				}
			},
			fmtlabel() {
				if (this.model.reportingMethod === '按数量') {
					if (this.model.processingType === '报废') {
						return '报废数量';
					} else {
						return '入库数量';
					}
				} else {
					if (this.model.processingType === '报废') {
						return '报废重量';
					} else {
						return '入库重量';
					}
				}
			},
			changeprocessingType() {
				this.model.reportedQuantity = '';
			},
			// 根据不良项数量 自动计算数量
			autoTotal() {
				let total = 0;
				this.model.ngList.forEach((item) => {
					total += item.ngNumber;
				});
				this.model.reportedQuantity = total;
			},
			open1() {
				this.$refs['uForm'].validate().then((valid) => {
					if (valid) this.$refs.popup1.open()
				});
			},
			open2() {
				this.$refs.popup2.open()
			},
			confirm1() {
				fetch('post', '/dms/mobileEnd/reworkOperation', null, {
					...this.model,
					applicationNumber: this.applicationNumber,
					shiftTime: this.dayjs(this.model.shiftTime).format('YYYY-MM-DD'),
					id: this.workInfo.id,
					workOrder: this.workInfo.workOrder,
				}).then(() => {
					this.$toast('操作成功');
					this.goto('/pages/workbench/rework/index');
				});
			},
			confirm2() {
				fetch('post', '/dms/mobileEnd/addRework', {
					applicationNumber: this.applicationNumber,
				}).then(() => {
					this.$toast('开始成功');
					this.getWorkOrderInfo(this.applicationNumber);
				});
			},
			goto(url) {
				uni.redirectTo({
					url,
					animationType: "pop-in",
					animationDuration: 1000,
				})
			},
			shiftTimeChange() {
				this.model.shift = '';
				this.getShiftList();
			},
			getShiftList() {
				fetch("get", "/dms/mobile/getShiftList", {
					deviceNo: getDevice().deviceNo,
					shiftDate: this.dayjs(this.model.shiftTime).format('YYYY-MM-DD'),
				}).then((res) => {
					this.shifts = res.map((item) => ({
						label: item.shift,
						value: item.shift,
						id: item.id
					}));
					if (this.shifts.length !== 0) {
						const has = res.find(item => timeIsBetweenTimeRange(filter.formatCurrentTimeDuration(),
							item.shiftStartTime,
							item.shiftEndTime));
						if (has) {
							this.model.shift = has.shift;
							this.model.shiftId = has.id;
						} else {
							this.model.shift = this.shifts[0].value;
							this.model.shiftId = this.shifts[0].id;
						}
					}
				});
			},
			getWareHouses() {
				fetch("get", "/dms/mobileEnd/getQualifiedWarehouse", {
					deviceNo: getDevice().deviceNo,
				}).then((res) => {
					if (res) {
						this.wareHouses = [{
							label: res.backupName,
							value: res.backupName,
							id: res.id,
						}];
						if (this.wareHouses.length !== 0)
							this.model.inboundWarehouse = this.wareHouses[0].value;
							this.model.warehouseId = this.wareHouses[0].id;
					}

				});
			},
			wareHouseChange(val){
				const arg=this.wareHouses.find(res=>res.label==val)
				if(arg){
					this.model.warehouseId = arg.id;
				}
			},
			getOutReasons() {
				fetch("get", "/dms/faultCategory/dictList", {
					name: "报废",
				}).then((res) => {
					this.reasons = res.map(item => {
						return {
							label: item.value,
							value: item.value
						}
					});
					if (this.reasons.length !== 0)
						this.model.outReason = this.reasons[0].value;
				});
			},
			getPoorList() {
				fetch("get", "/dms/faultCategory/dictList", {
					name: "不良项",
				}).then((res) => {
					this.model.ngList = res.map(item => {
						return {
							ngCode: item.value,
							ngNumber: 0,
						}
					});
				});
			},
		},
		onLoad(params) {
			this.applicationNumber = params.applicationNumber;
			this.getWorkOrderInfo(params.applicationNumber);
			this.getShiftList();
			this.getWareHouses();
			this.getOutReasons();
			this.getPoorList();
		}
	};
</script>

<style scoped lang="scss">
	.left {
		flex: 0 auto;
		width: 50rem;
		background: #f8f8fa;
	}

	.right {
		flex: 1;
		background-color: red;
		background: #fff;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;
		padding: 3rem 4rem 5rem;
	}

	.ng-list {
		display: flex;
		flex-wrap: wrap;

		/deep/ .u-form-item {
			width: 45%;
			margin-left: 3%;
		}
	}

	.label-fwn {
		/deep/ .u-form-item__body__left__content__label {
			font-weight: normal !important;
		}
	}

	.sub-title {
		padding: 3rem 0;
		font-size: 2.2rem;
		font-weight: bold;
		border-bottom: 1px solid #ccc;
		margin: 2rem 0;
	}

	/deep/ .form-wrap .body {
		padding-top: 0;
	}

	.label-top {
		/deep/ .u-form-item__body__left {
			align-items: flex-start !important;
			margin-top: 2.7rem;
		}
	}

	.label-fwn {
		/deep/ .u-form-item__body__left__content__label {
			font-weight: normal !important;
		}
	}
</style>